package com.neusoft.resturant.controller;

import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.utils.R;
import com.neusoft.resturant.entity.ResShop;
import com.neusoft.resturant.mapper.ResShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: resturant
 * @description:
 * @author: lydms
 * @create: 2023-11-22 13:41
 **/

@RestController
@RequestMapping("/api/redis")
public class RedisController {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private ResShopMapper shopMapper;

    @GetMapping("/put")
    public R put(String key,String value){

        System.out.println("key:"+key);
        System.out.println("value"+value);
        redisTemplate.opsForValue().set(key,value,1, TimeUnit.DAYS);

        String v = (String) redisTemplate.opsForValue().get(key);

        Map result = new HashMap();
        result.put("key",key);
        result.put("value",value);
        return R.success(result);
    }

    @GetMapping("/putObj")
    public R putObj(@RequestParam Long id) {
        // 1、从Mysql数据库中查询店铺id为18的店铺
        ResShop resShop = shopMapper.selectResShopById(id);
        String json = JSON.toJSONString(resShop);
        System.out.println(json);
        // 2、店铺放到redis
        redisTemplate.opsForValue().set(id.toString(), json, 1, TimeUnit.HOURS);
        return R.success(resShop);
    }


    @GetMapping("/getObj")
    public R getObj(@RequestParam Long id) {
        String json = (String) redisTemplate.opsForValue().get(id.toString());
        System.out.println(json);
        ResShop resShop = new ResShop();
        if (json == null) {
            System.out.println("redis 没有该信息");
            // 1、从Mysql数据库中查询店铺id为18的店铺
            resShop = shopMapper.selectResShopById(id);
            String shopStr = JSON.toJSONString(resShop);
            System.out.println(shopStr);
            // 2、店铺放到redis
            redisTemplate.opsForValue().set(id.toString(), shopStr, 1, TimeUnit.HOURS);
        } else {
            System.out.println("redis 中存在该信息：" + json);
            resShop = JSON.parseObject(json, ResShop.class);
        }
        return R.success(resShop);
    }




}
